const wxRequest = require('../../utils/js/wxRequest.js');
const wxaapi = require('../wxaapi.js');
var fGetUserByUnionId = function (unionid, callback) {
  wx.request({
    url: wxaapi.user.userinfo.url,
    method: "POST",
    data: { unionid: unionid },
    header: {
      'Content-Type': 'application/json'
    },
    success: function (result) {
      //console.log("user info result===>",result);
      callback(result);
    }
  });
};
/**
* 获取用户token
*/
var fGetUserToken = function (unionid,callback) {
  let _This = this;
  //let maxSegTime=3600*60*60*5;//5小时
  let maxSegTime = 3600 * 60;
  let currentTime = new Date().getTime();
  let tokenexpire = wx.getStorageSync("tokenexpire");
  let localToken = wx.getStorageSync("localToken");
  if (localToken && tokenexpire && (currentTime - tokenexpire < maxSegTime)) {
    //callback(true);
    return fGetUserPermission(unionid);
  } else {
    let pdata = { unionid: unionid};
    return wxRequest(wxaapi.user.usertoken.url, pdata).then(function (result) {
      localToken = result.data.data || "";
      if (result.data.code == 0) {
        wx.setStorageSync("localToken", localToken);
        wx.setStorageSync("tokenexpire", currentTime);
        callback(true);
      } else {
        callback(false);
      }
      return fGetUserPermission(unionid);

    });
  }
};
/**
 * 获取用户权限列表
 */
function fGetUserPermission(unionid){

  var _This = this;
  let pdata = { unionid: unionid }; //
  return wxRequest(wxaapi.user.userinfo.url, pdata).then(function (result) {
    let userId ="0";
    if (result.data.code== 0) {
      userId = result.data.data.id; 
    let pResourceData = { userId: userId };
    //return wxRequest(wxaapi.user.userresources.url, pResourceData);
    return wxRequest(wxaapi.user.userpermission.url, pResourceData);
    }else{
      return {data:{}};
    }
  }).then(function(result){
    let stimes= wx.getStorageSync("stimes");
     if (result.data.exception && !stimes){
       wx.setStorageSync("stimes", "OK");
      wx.removeStorageSync("localToken");
      return fGetUserToken(unionid,function(){});
    }else{
      wx.setStorageSync("stimes", "");
      let permissionData = result.data.data;
      let aPermission = Array.isArray(permissionData)?permissionData:[];
      //console.log("permissionData---------------", permissionData);
      return aPermission;
    }
 
  });

};


module.exports = {
  fGetUserByUnionId: fGetUserByUnionId,
  fGetUserToken: fGetUserToken,
  fGetUserPermission: fGetUserPermission
}